<template>
  <div class="level-adjustment-record">
    <el-card>
      <div slot="header">
        <span>调级记录查询</span>
      </div>

      <!-- 查询条件 -->
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="日期范围">
          <el-date-picker
              v-model="queryForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="员工">
          <el-select v-model="queryForm.employeeId" placeholder="请选择员工" clearable>
            <el-option
                v-for="emp in employees"
                :key="emp.employeeId"
                :label="emp.employeeName"
                :value="emp.employeeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
        <el-button
            type="danger"
            @click="printCSV"
        >打印</el-button>
      </el-form>

      <!-- 调级记录列表 -->
      <el-table
          :data="recordList"
          border
          style="width: 100%"
          v-loading="loading"
          :element-loading-text="loadingText"
      >
        <el-table-column
            prop="employeeName"
            label="员工姓名"
            width="120">
        </el-table-column>
        <el-table-column
            prop="employeeNo"
            label="员工号"
            width="120">
        </el-table-column>
        <el-table-column
            prop="oldLevelName"
            label="原薪资级别"
            width="150">
        </el-table-column>
        <el-table-column
            prop="newLevelName"
            label="新薪资级别"
            width="150">
        </el-table-column>
        <el-table-column
            prop="adjustmentDate"
            label="调级日期"
            width="150">
        </el-table-column>
        <el-table-column
            prop="operatorName"
            label="操作人"
            width="120">
        </el-table-column>
        <el-table-column
            prop="remark"
            label="备注">
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import {getAdjustmentRecords, getAllEmployees} from '@/api/levelAdjustment'

export default {
  name: 'LevelAdjustmentRecord',
  data() {
    return {
      queryForm: {
        dateRange: [],
        employeeId: null
      },
      recordList: [],
      employees: [],
      loading: false,
      loadingText: '正在加载数据...',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      }
    }
  },
  created() {
    this.fetchEmployees()
    this.fetchRecords()
  },
  methods: {
    fetchEmployees() {
      this.loading = true
      getAllEmployees()
          .then(response => {
            if (response.data.code === 200) {
              this.employees = response.data.data || []
            } else {
              this.$message.error('获取员工列表失败')
              this.employees = []
            }
          })
          .catch(error => {
            console.error('获取员工失败:', error)
            this.$message.error('获取员工列表失败')
            this.employees = []
          })
          .finally(() => {
            this.loading = false
          })
    },
    async fetchRecords() {
      this.loading = true
      const params = {}
      if (this.queryForm.dateRange && this.queryForm.dateRange.length === 2) {
        params.startDate = this.queryForm.dateRange[0]
        params.endDate = this.queryForm.dateRange[1]
      }
      if (this.queryForm.employeeId) {
        params.employeeId = this.queryForm.employeeId
      }
      console.log(params)
      getAdjustmentRecords(params)
          .then(response => {
            console.log(response)
            if (response.data.code === 200) {
              console.log(response.data)
              this.recordList = response.data.data.map(item => ({
                adjustmentId: item.adjustmentId,
                employeeId: item.employeeId,
                employeeName: item.employeeName,
                employeeNo: item.employeeNo || '--', // 处理 null
                oldLevelName: item.oldLevelName,
                newLevelName: item.newLevelName,
                adjustmentDate: this.formatDate(item.adjustmentDate), // 格式化时间
                operatorName: item.operatorName,
                remark: item.remark || '--'
              }))
            } else {
              this.$message.error('获取调级记录失败')
              this.recordList = []
            }
          })
          .catch(error => {
            console.error('请求错误:', error)
            this.$message.error('获取调级记录失败')
            this.recordList = []
          })
          .finally(() => {
            this.loading = false
          })
    },
    handleQuery() {
      if (!this.queryForm.dateRange || this.queryForm.dateRange.length !== 2) {
        this.$message.error('请选择完整的日期范围')
        return
      }
      this.fetchRecords()
    },
    formatDate(dateString) {
      if (!dateString) return '--'
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    printCSV() {
      // 1. 创建CSV内容（包含BOM头解决中文乱码）
      const csvContent = "\uFEFF年休假申请记录\n\n";

      // 2. 创建CSV表头
      const headers = [
        "员工ID",
        "员工姓名",
        "部门",
        "申请日期",
        "开始日期",
        "结束日期",
        "休假天数",
        "休假类型",
        "休假原因",
        "审批状态",
        "审批人",
        "备注"
      ].join(",") + "\n";

      // 3. 创建Blob对象
      const blob = new Blob([csvContent + headers], {
        type: 'text/csv;charset=utf-8;'
      });

      // 4. 创建下载链接
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.href = url;

      // 5. 设置文件名（使用当前年月日）
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      link.setAttribute('download', `年休假申请记录_${year}${month}${day}.csv`);

      // 6. 触发下载
      document.body.appendChild(link);
      link.click();

      // 7. 清理
      setTimeout(() => {
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
      }, 100);
    }
  }
}
</script>
<style scoped>
.level-adjustment-record {
  padding: 20px;
}

.employee-table {
  width: 100%;
  border-collapse: collapse;
}

.employee-table th,
.employee-table td {
  border: 1px solid #ebeef5;
  padding: 8px;
  text-align: center;
}

.loading-text {
  color: #999;
  font-size: 14px;
}

.error-text {
  color: red;
  font-size: 14px;
}
</style>